//
//  CacheDaoForCircleContent.m
//  GolfFriend
//
//  Created by Vescky on 13-12-13.
//  Copyright (c) 2013年 vescky.org. All rights reserved.
//

#import "CacheDaoForCircleContent.h"
#import "JSON.h"
#import "DateUtility.h"

#define TB_CIRCLE_CONTENT_CACHE @"CIRCLE_CONTENT_CACHE"

@implementation CacheDaoForCircleContent

CacheDaoForCircleContent *cacheForCC;

#pragma mark - Private
- (bool)isArticleRecordExist:(NSString*)aId {
    if ([self getCacheDataWithArticleId:aId]) {
        return YES;
    }
    return NO;
}


#pragma mark - Public
+ (id)shareCacheDaoForCircleContent {
    if (!cacheForCC) {
        cacheForCC = [[CacheDaoForCircleContent alloc] init];
        DB *dbase = [[DB alloc] init];
        FMDatabase *database = [dbase getDatabase];
        [database executeUpdate:[NSString stringWithFormat:@"CREATE TABLE IF NOT EXISTS %@(recordId integer primary key,articleId text,userId text,content text,userName text,userNickName text,avatar text,time text,sourceLinks text,clicks text,comments text,zan text,isSupported text)",TB_CIRCLE_CONTENT_CACHE]];
        [database close];
    }
    return cacheForCC;
}

//更新单个
- (bool)updateCacheDataWithCircleContent:(CircleContentVO*)cVo {
    
    NSMutableDictionary *params = [[NSMutableDictionary alloc] initWithObjectsAndKeys:cVo.userId,@"userId",
                                   cVo.articleId,@"articleId",
                                   cVo.content,@"content",
                                   cVo.userName,@"userName",
                                   cVo.userNickName,@"userNickName",
                                   cVo.avatar,@"avatar",
                                   cVo.time,@"time",
                                   cVo.clicks,@"clicks",
                                   cVo.comments,@"comments",
                                   cVo.zan,@"zan",
                                   cVo.isSupported,@"isSupported",
                                   [cVo.sourceLinks JSONFragment],@"sourceLinks", nil];
    
    
    if (!params || [params count] < 1) {
        return NO;
    }
    
    if ([self isArticleRecordExist:cVo.articleId]) {
        //有记录的，update
        [self update:params where:[[NSMutableDictionary alloc] initWithObjectsAndKeys:cVo.articleId,@"articleId",nil] inTable:TB_CIRCLE_CONTENT_CACHE];
    }
    else {
        //无记录的，insert
        [self insert:params inTable:TB_CIRCLE_CONTENT_CACHE];
    }
    
    return YES;
}

- (bool)deleteArticleContent:(CircleContentVO*)cVo {
    if ([self isArticleRecordExist:cVo.articleId]) {
        //有记录的，update
        [self remove:@"articleId" is:cVo.articleId inTable:TB_CIRCLE_CONTENT_CACHE];
        return YES;
    }
    return NO;
    
}

//更新一个数组
- (bool)updateCacheDataWithCircleContentArray:(NSArray*)cVoArray {
    if (cVoArray.description.length < 1) {
        return NO;
    }
    if (![cVoArray respondsToSelector:@selector(count)]) {
        return NO;
    }
    for (int i = 0; i < [cVoArray count]; i++) {
        CircleContentVO *cVo = [cVoArray objectAtIndex:i];
        if (cVo) {
            [self updateCacheDataWithCircleContent:cVo];
        }
    }
    return YES;
}

//获取一个数组
- (NSMutableArray*)getCacheDataLimitRow:(NSRange)limitRange {
    NSMutableArray *allData = [self queryAll:TB_CIRCLE_CONTENT_CACHE];
    NSMutableArray *resultArr = [[NSMutableArray alloc] init];
    for (int i = 0; i < [allData count]; i++) {
        NSMutableDictionary *_dict = [[NSMutableDictionary alloc] initWithDictionary:[allData objectAtIndex:i]];
        NSDictionary *sourceDict = [[_dict objectForKey:@"sourceLinks"] JSONValue];
        if (sourceDict) {
            [_dict setObject:sourceDict forKey:@"sourceLinks"];
        }
        CircleContentVO *cVo = [[CircleContentVO alloc] init];
        [cVo dictionaryToCircleContentVO:_dict];
        if (cVo) {
            [resultArr addObject:cVo];
        }
    }
    
    //按时间，从晚到早排序
    NSArray *sortedArr = [resultArr sortedArrayUsingComparator:^NSComparisonResult(id obj1, id obj2) {
        CircleContentVO *cVo1 = obj1;
        CircleContentVO *cVo2 = obj2;
        NSDate *date1 = getDateFromString(@"yyyy-MM-dd HH:mm:ss", cVo1.time);
        NSDate *date2 = getDateFromString(@"yyyy-MM-dd HH:mm:ss", cVo2.time);
        if ([date1 isEqualToDate:[date1 laterDate:date2]]) {
            return (NSComparisonResult)NSOrderedAscending;
        }
        else {
            return (NSComparisonResult)NSOrderedDescending;
        }
        
        return (NSComparisonResult)NSOrderedSame;
    }];
    
    NSMutableArray *arrLimitted = [[NSMutableArray alloc] init];
    if ([sortedArr count] > limitRange.length) {
        arrLimitted = [[NSMutableArray alloc] initWithArray:[sortedArr subarrayWithRange:limitRange]];
    }
    else {
        arrLimitted = [[NSMutableArray alloc] initWithArray:sortedArr];
    }
    
    return arrLimitted;
}

- (NSMutableArray*)getArticlesPublishedByUser:(NSString*)userId range:(NSRange)limitRange {
    NSString *sqlString = [NSString stringWithFormat:@"select * from %@ where userId = '%@'",TB_CIRCLE_CONTENT_CACHE,userId];
    NSMutableArray *allData = [self queryByConfition:sqlString];
    NSMutableArray *resultArr = [[NSMutableArray alloc] init];
    for (int i = 0; i < [allData count]; i++) {
        NSMutableDictionary *_dict = [[NSMutableDictionary alloc] initWithDictionary:[allData objectAtIndex:i]];
        NSDictionary *sourceDict = [[_dict objectForKey:@"sourceLinks"] JSONValue];
        if (sourceDict) {
            [_dict setObject:sourceDict forKey:@"sourceLinks"];
        }
        CircleContentVO *cVo = [[CircleContentVO alloc] init];
        [cVo dictionaryToCircleContentVO:_dict];
        if (cVo) {
            [resultArr addObject:cVo];
        }
    }
    
    //按时间，从晚到早排序
    NSArray *sortedArr = [resultArr sortedArrayUsingComparator:^NSComparisonResult(id obj1, id obj2) {
        CircleContentVO *cVo1 = obj1;
        CircleContentVO *cVo2 = obj2;
        NSDate *date1 = getDateFromString(@"yyyy-MM-dd HH:mm:ss", cVo1.time);
        NSDate *date2 = getDateFromString(@"yyyy-MM-dd HH:mm:ss", cVo2.time);
        if ([date1 isEqualToDate:[date1 laterDate:date2]]) {
            return (NSComparisonResult)NSOrderedAscending;
        }
        else {
            return (NSComparisonResult)NSOrderedDescending;
        }
        
        return (NSComparisonResult)NSOrderedSame;
    }];
    
    NSMutableArray *arrLimitted = [[NSMutableArray alloc] init];
    if ([sortedArr count] > limitRange.length) {
        arrLimitted = [[NSMutableArray alloc] initWithArray:[sortedArr subarrayWithRange:limitRange]];
    }
    else {
        arrLimitted = [[NSMutableArray alloc] initWithArray:sortedArr];
    }
    
    return arrLimitted;
}

//获取单个
- (CircleContentVO*)getCacheDataWithArticleId:(NSString*)rId {
    NSString *sqlString = [NSString stringWithFormat:@"select * from %@ where articleId = '%@'",TB_CIRCLE_CONTENT_CACHE,rId];
    NSMutableArray *rArr = [self queryByConfition:sqlString];
    if (rArr && [rArr count] > 0) {
        NSMutableDictionary *_dict = [[NSMutableDictionary alloc] initWithDictionary:[rArr objectAtIndex:0]];
        NSDictionary *sourceDict = [[_dict objectForKey:@"sourceLinks"] JSONValue];
        if (sourceDict) {
            [_dict setObject:sourceDict forKey:@"sourceLinks"];
        }
        CircleContentVO *cVo = [[CircleContentVO alloc] init];
        [cVo dictionaryToCircleContentVO:_dict];
        if (cVo) {
            return cVo;
        }
    }
    
    return nil;
}

- (bool)cleanupCache {
    DB *dbase = [[DB alloc] init];
    FMDatabase *database = [dbase getDatabase];
    bool flag = [database executeUpdate:[NSString stringWithFormat:@"delete from %@",TB_CIRCLE_CONTENT_CACHE]];
    if (flag) {
        flag = [database executeUpdate:[NSString stringWithFormat:@"update sqlite_sequence set seq=0 where name = '%@'",TB_CIRCLE_CONTENT_CACHE]];
        
    }
    [database close];
    return flag;
}

@end
